package com.trip.admin;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trip.api.ControllerResult;
import com.trip.dao.tables.pojos.AdminDomain;
import com.trip.def.CommonDefines;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by hc24 on 2017/12/26.
 */
@WebFilter(urlPatterns="/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session=request.getSession();

        AdminDomain admin= (AdminDomain) session.getAttribute(CommonDefines.ADMIN_SESSION);
        String path=request.getServletPath();
        if(path.endsWith(".jsp")||path.endsWith(".html")||path.startsWith("/admin/")){
            if(admin==null){
                doTimeout(request,response,path);
            }
        }

        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }

    private void doTimeout(HttpServletRequest httpRequest,HttpServletResponse httpResponse,String url) throws IOException, ServletException {
        String httpAjax = httpRequest.getHeader("X-Requested-With");
        if (httpAjax != null && "XMLHttpRequest".equals(httpAjax)) {// 判断ajax请求
            if (url.contains(".jsp")) {
                httpResponse.sendRedirect(httpRequest.getContextPath()
                        + "/login");
            } else {
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("application/json");
                PrintWriter out = httpResponse.getWriter();

                ObjectMapper objectMapper = new ObjectMapper();
                JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(out);
                jsonGenerator.writeObject(ControllerResult.failed("Session time out"));
                out.flush();
                out.close();
                return;
            }
        } else {// 非AJAX请求
            httpResponse.sendRedirect(httpRequest.getContextPath()
                    + "/login");
        }
    }
}
